package com.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import org.apache.log4j.Logger;

public class FileOperate {
	private Logger log = Logger.getLogger(this.getClass());
	
	public FileOperate() {
	}
	
	  /**
	   * 把file1path,file2path指定的文件的内容连接起来并写入用file3path指定的文件
	   * @param file1path
	   * @param file2path
	   * @param file3path
	   */
	public File[] getFileList(String filepath){
		  File d=null;
		  File list[]=null;
//		建立当前目录中文件的File对象
		  try{
		   d=new File(filepath);
		   if(d.exists()){
		   list=d.listFiles();
		   } 
		  }
		  catch(Exception ex){
			  ex.printStackTrace();
		  }
//		取得代表目录中所有文件的File对象数组   
		 
		return list;
	  }
	
	  public File[] getFileList(String filepath,FileFilter filter){
		  File d=null;
		  File list[]=null;
//		建立当前目录中文件的File对象
		  try{
		   d=new File(filepath);
		   if(d.exists()){
		   list=d.listFiles(filter);
		   } 
		  }
		  catch(Exception ex){
			  ex.printStackTrace();
		  }
//		取得代表目录中所有文件的File对象数组   
		 
		return list;
	  }
	 
	  public File concatNewFile(String file1path,String file2path,String file3path){
		  File file1=new File(file1path);
		  File file2=new File(file2path);
		  File file3=new File(file3path);
		  int fileflag=0;
		  if(!file3.exists()){
			  
			  try {
					file3.createNewFile();
					fileflag=1;
				} catch (IOException e) {
					// TODO 自动生成 catch 块
					e.printStackTrace();
				}
			  
		  }
		try {
			FileReader read1= new FileReader(file1);
			FileReader read2=new FileReader(file2);
			BufferedReader bread1=new BufferedReader(read1);
			BufferedReader bread2=new BufferedReader(read2);
			FileWriter write=new FileWriter(file3);
			
			boolean ch=true;
			boolean ch1=true;
			BufferedWriter bwrite=new BufferedWriter(write);
			while(ch){
			String data=bread1.readLine();
			System.out.println("data:"+data);
			if(data!=null&&!data.equals("")){
			System.out.println("-----------------------------");
			System.out.println("data:"+data);
			System.out.println("+++++++++++++++++++++++++++++++++");
			bwrite.flush();
			bwrite.write(data);
			bwrite.newLine();
			
			}
			
			if(data==null||data.equals("")){
				ch=false;
				
			}
			
			}
			while(ch1){
				
				String data1=bread2.readLine();
				System.out.println("data111111111:"+data1);
				if(data1!=null&&!data1.equals("")){
				bwrite.flush();	
				bwrite.write(data1);
				bwrite.newLine();
				}
				
				if(data1==null||data1.equals("")){
					ch1=false;
					
				}
				
				
			}
			bread2.close();
	bread1.close();
		read1.close();
	read2.close();
		bwrite.close();
		write.close();
			
			
			
			
			  
		} catch (FileNotFoundException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
		 
		  return file3;
		  
	  }
	  /**
	   * 把file2path指定的文件的内容写入用file1path指定的文件
	   *
	   */
	  public void concatFile(String file1path,String file2path){
		  File file1=new File(file1path);
		  File file2=new File(file2path);
		  byte[] data=new byte[59];
		  String datastr="";
		  if(!file1.exists()){
				
				try {
					file1.createNewFile();
					
				} catch (IOException e) {
					// TODO 自动生成 catch 块
					e.printStackTrace();
				}
		
			}
		  if(!file2.exists()){
				
				try {
					file2.createNewFile();
					
				} catch (IOException e) {
					// TODO 自动生成 catch 块
					e.printStackTrace();
				}
		
			}
		  try {
			  
			  FileWriter writer=new FileWriter(file1,true);
			   BufferedWriter bwriter=new BufferedWriter(writer);
			
			 FileInputStream  in=new FileInputStream(file2);
			 in.read(data);
			 datastr=new String(data);
			 bwriter.newLine();
			 bwriter.write(datastr);
			 bwriter.close();
			 writer.close();
			
			 in.close();
			
			 
		} catch (FileNotFoundException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
		 
		  
			
			
		  
	  }
	  /**
	   * 新建目录
	   * @param folderPath String 如 c:/fqf
	   * @return boolean
	   */
	  public  void newFolder(String folderPath) {
	    try {
	      String filePath = folderPath;
	      filePath = filePath.toString();
	      java.io.File myFilePath = new java.io.File(filePath);
	      if (!myFilePath.exists()) {
	        myFilePath.mkdir();
	      }
	    }
	    catch (Exception e) {
	      System.out.println("新建目录操作出错");
	      e.printStackTrace();
	    }
	  }
	  public void newFolder2(String folderPath){
		//  String folderPaht="c:/aaa/";
		  folderPath=folderPath.toString();//中文转换
		  java.io.File myFilePath=new java.io.File(folderPath);
		  if(!myFilePath.exists())
		  myFilePath.mkdir();

	  }
	  /**
	   * 新建文件
	   * @param filePathAndName String 文件路径及名称 如c:/fqf.txt
	   * @param fileContent String 文件内容
	   * @return boolean
	   */
	  public void newFile(String filePathAndName, String fileContent) {
	    try {
	      String filePath = filePathAndName;
	      filePath = filePath.toString();
	      File myFilePath = new File(filePath);
	      if (!myFilePath.exists()) {
	        myFilePath.createNewFile();
	      }
	      FileWriter resultFile = new FileWriter(myFilePath);
	      PrintWriter myFile = new PrintWriter(resultFile);
	      String strContent = fileContent;
	      myFile.println(strContent);
	      resultFile.close();
	    }
	    catch (Exception e) {
	      System.out.println("新建目录操作出错");
	      e.printStackTrace();
	    }
	  }
	  /**
	   * 获得文件的 输入流并设置读文件的编码方式，有效解决乱码问题（这个乱码主要出现在系统编码方式不能读取文件是令一种编码方式的情况例如：UTF-8而要读取Big5的文件的情况)。
	   * @param filepath
	   * @param encoding
	   * @return
	   */
	  
	  public BufferedReader getCodeFileBuffReader(String filepath,String encoding){
			 BufferedReader brin=null;
			 File newf=new File(filepath);
			 if (!newf.exists()) {
			        try {
						newf.createNewFile();
					} 
			        
			        catch (IOException e) {
						// TODO 自动生成 catch 块
						e.printStackTrace();
					}
			      }
			 try{// brin = new BufferedReader(new InputStreamReader(new FileInputStream(newf), "big5"));
				 brin = new BufferedReader(new InputStreamReader(new FileInputStream(newf), encoding));
				    }
				catch(Exception ex){
				           brin=null;
				}
				
		return brin;
		  
	  }
	 /**
	  * 获得文件的输出流
	  * @param filepath
	  * @return
	  */
	  public FileReader getFileReader(String filepath){
		  FileReader reader=null;
		  try{
			  File myFile=new File(filepath);
			  if (!myFile.exists()) {
			      reader=null;
			      }
			   reader=new FileReader(myFile);
		
			  }
		  catch(Exception ex){
			  System.out.println("新建目录操作出错");
		      ex.printStackTrace();
			  
		  }
		  return reader;
	  }
	  /**
	   * 获得文件输入流
	   * @param filepath
	   * @return
	   */
	  
	  public FileWriter getFileWriter(String filepath){
		  FileWriter writer=null;
		  try{
			  File myFile=new File(filepath);
			  if (!myFile.exists()) {
			      writer=null;
			      }
			   writer=new FileWriter(myFile);
		
			  }
		  catch(Exception ex){
			  System.out.println("新建目录操作出错");
		      ex.printStackTrace();
			  
		  }
		  return writer;
	  }
	  /**
	   * 关闭输入或输出流，
	   * @param filepipe
	   * @param sigh  sigh=true,FileWriter sigh=false FileReader
	   */
	  public void closeFilePipe(Object filepipe,boolean sigh){
		 
		  if(sigh){
			  FileWriter writer=(FileWriter)filepipe;
			  try{
				  writer.close();
				  
			  }
			  catch(Exception ex){
				  ex.printStackTrace();
			  }
		  }
			  
			  else{
				  FileReader reader=(FileReader)filepipe;
				  try{
					  reader.close();
					  
				  }
				  catch(Exception ex){
					  ex.printStackTrace();
				  }
				  
			  }
		  }
		  
		  
		  
		  
		  
	  
	  
	  
	  
	  /**
	   * 删除文件
	   * @param filePathAndName String 文件路径及名称 如c:/fqf.txt
	   * @param fileContent String
	   * @return boolean
	   */
	  public void delFile(String filePathAndName) {
	    try {
	      String filePath = filePathAndName;
	      filePath = filePath.toString();
	      java.io.File myDelFile = new java.io.File(filePath);
	      if(myDelFile.exists()){
	      myDelFile.delete();}
	    }
	    catch (Exception e) {
	      System.out.println("删除文件操作出错");
	      e.printStackTrace();
	    }
	  }
	  /**
	   * 删除文件夹
	   * @param filePathAndName String 文件夹路径及名称 如c:/fqf
	   * @param fileContent String
	   * @return boolean
	   */
	  public void delFolder(String folderPath) {
	    try {
	      delAllFile(folderPath); //删除完里面所有内容
	      String filePath = folderPath;
	      filePath = filePath.toString();
	      java.io.File myFilePath = new java.io.File(filePath);
	      myFilePath.delete(); //删除空文件夹
	    }
	    catch (Exception e) {
	      System.out.println("删除文件夹操作出错");
	      e.printStackTrace();
	    }
	  }
	  /**
	   * 删除文件夹里面的所有文件
	   * @param path String 文件夹路径 如 c:/fqf
	   */
	  public void delAllFile(String path) {
	    File file = new File(path);
	    if (!file.exists()) {
	      return;
	    }
	    if (!file.isDirectory()) {
	      return;
	    }
	    String[] tempList = file.list();
	    File temp = null;
	    for (int i = 0; i < tempList.length; i++) {
	      if (path.endsWith(File.separator)) {
	        temp = new File(path + tempList[i]);
	      }
	      else {
	        temp = new File(path + File.separator + tempList[i]);
	      }
	      if (temp.isFile()) {
	        temp.delete();
	      }
	      if (temp.isDirectory()) {
	        delAllFile(path+"/"+ tempList[i]);//先删除文件夹里面的文件
	        delFolder(path+"/"+ tempList[i]);//再删除空文件夹
	      }
	    }
	  }
	  
	  public void copyFile(String oldPath,String newPath,String encoding){
		  log.info("newPath===="+newPath);
	    	String path = newPath.substring(0,newPath.lastIndexOf(System.getProperties().getProperty("file.separator")));
	    	log.info("path===="+path);
	    	(new File(path)).mkdirs();
		    try {
		      File oldfile = new File(oldPath);
		      File newfile=new File(newPath);
		      if(!newfile.exists()){
		    	  newfile.createNewFile();
		      }
		      //System.out.println(newfile.getName());
		      if (oldfile.exists()) { 
		      BufferedWriter outStream=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newfile),encoding));
		      BufferedReader inStream = new BufferedReader(new InputStreamReader(new FileInputStream(oldfile), encoding));
		      StringBuffer strin= new StringBuffer();
		      String s;
		      while((s=inStream.readLine()) != null) {
		        	outStream.write(s);
		        	outStream.newLine();
		        	outStream.flush();
				    strin.append(s);
				    strin.append("\n");
				    
				  }
		        inStream.close();
		        outStream.close();
		      }
		    }
		    catch (Exception e) {
		      System.out.println("复制单个文件操作出错");
		      e.printStackTrace();
		    }
		  
		  
	  }
	  /**
	   * 以文件流的方式复制单个文件
	   * @param oldPath String 原文件路径 如：c:/fqf.txt
	   * @param newPath String 复制后路径 如：f:/fqf.txt
	   * @return boolean
	   */
/*	  public void copyFile(String oldPath, String newPath) {
	    try {
	    	log.info("newPath===="+newPath);
	    	String path = newPath.substring(0,newPath.lastIndexOf(System.getProperties().getProperty("file.separator")));
	    	log.info("path===="+path);
	    	(new File(path)).mkdirs(); 
	    	
	      int bytesum = 0;
	      int byteread = 0;
	      File oldfile = new File(oldPath);
	      File newfile=new File(newPath);
	      
	      if(!newfile.exists()){
	    	  newfile.createNewFile();
	      }
	      System.out.println(newfile.getName());
	      if (oldfile.exists()) { //文件存在时
	        //InputStream inStream = new FileInputStream(oldfile); //读入原文件
	        //InputStream inStream=(InputStream)new InputStreamReader(new FileInputStream(oldfile),"big5");
	       //InputStreamReader inStream =new InputStreamReader(new FileInputStream(oldfile), "big5");
	       OutputStreamWriter fs = new OutputStreamWriter(new FileOutputStream(newfile));
	       BufferedWriter outStream=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newfile)));
	       BufferedReader inStream = new BufferedReader(new InputStreamReader(new FileInputStream(oldfile)));
	       char[] buffer = new char[20];
	       StringBuffer strin= new StringBuffer();
	       String s;
	        int length;
	       // while ( (byteread =inStream.read(buffer)) != -1) {
	      //    bytesum += byteread; //字节数 文件大小
	       //   System.out.println(bytesum);
	       //   System.out.println(buffer.toString());
	         // for(int i=0;i<byteread-1;i++){
	        //	 System.out.println(buffer[i]);
	         // }
	          //if(bytesum<280)
	        //  fs.write(buffer, 0, byteread);
	      //  }
	        while((s=inStream.readLine()) != null) {
	        	//System.out.println("ss:"+s);
	        	
	        	outStream.write(s);
	        	outStream.newLine();
	        	outStream.flush();
			    strin.append(s);
			    strin.append("\n");
			    
			  }
	        inStream.close();
	        outStream.close();
	      }
	    }
	    catch (Exception e) {
	      System.out.println("复制单个文件操作出错");
	      e.printStackTrace();
	    }
	  }*/
	  
	  public  void  copyFile(String  oldPath,  String  newPath)  {      
	       try  {      
	    	   String path = newPath.substring(0,newPath.lastIndexOf(System.getProperties().getProperty("file.separator")));
		    	log.info("path===="+path);
		    	(new File(path)).mkdirs(); 
	           int  bytesum  =  0;      
	           int  byteread  =  0;      
	           File  oldfile  =  new  File(oldPath);      
	           if  (oldfile.exists())  {  //文件存在时      
	               InputStream  inStream  =  new  FileInputStream(oldPath);  //读入原文件      
	               FileOutputStream  fs  =  new  FileOutputStream(newPath);      
	               byte[]  buffer  =  new  byte[1444];      
	               int  length;      
	               while  (  (byteread  =  inStream.read(buffer))  !=  -1)  {      
	                   bytesum  +=  byteread;  //字节数  文件大小      
	                   //System.out.println(bytesum);      
	                   fs.write(buffer,  0,  byteread);      
	               }      
	               inStream.close();      
	           }      
	       }      
	       catch  (Exception  e)  {      
	           System.out.println("复制单个文件操作出错");      
	           e.printStackTrace();      
	     
	       }      
	     
	   }      

	  /**
	   * 复制整个文件夹内容
	   * @param oldPath String 原文件路径 如：c:/fqf
	   * @param newPath String 复制后路径 如：f:/fqf/ff
	   * @return boolean
	   */
	  public void copyFolder(String oldPath, String newPath) {
	    try {
	      (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
	      File a=new File(oldPath);
	      String[] file=a.list();
	      File temp=null;
	      for (int i = 0; i < file.length; i++) {
	        if(oldPath.endsWith(File.separator)){
	          temp=new File(oldPath+file[i]);
	        }
	        else{
	          temp=new File(oldPath+File.separator+file[i]);
	        }
	        if(temp.isFile()){
	          FileInputStream input = new FileInputStream(temp);
	          FileOutputStream output = new FileOutputStream(newPath + "/" +
	              (temp.getName()).toString());
	          byte[] b = new byte[1024 * 5];
	          int len;
	          while ( (len = input.read(b)) != -1) {
	            output.write(b, 0, len);
	          }
	          output.flush();
	          output.close();
	          input.close();
	        }
	        if(temp.isDirectory()){//如果是子文件夹
	          copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
	        }
	      }
	    }
	    catch (Exception e) {
	      System.out.println("复制整个文件夹内容操作出错");
	      e.printStackTrace();
	    }
	  }
	  /**
	   * 移动文件到指定目录
	   * @param oldPath String 如：c:/fqf.txt
	   * @param newPath String 如：d:/fqf.txt
	   */
	  public void moveFile(String oldPath, String newPath) {
	    copyFile(oldPath, newPath);
	    delFile(oldPath);
	  }
	  public String getInputMessage() throws IOException{ 
		  String str="";
		  System.out.println("请输入您的命令∶"); 
		  byte buffer[]=new byte[1024]; 
		  int count=System.in.read(buffer); 
		  char[] ch=new char[count-2];//最后两位为结束符，删去不要 
		  for(int i=0;i<ch.length;i++){
		  ch[i]=(char)buffer[i]; 
		  str=new String(ch); 
		 } 
		  return str; 
	  }
	  /**
	   * 移动文件到指定目录
	   * @param oldPath String 如：c:/fqf.txt
	   * @param newPath String 如：d:/fqf.txt
	   */
	  public void moveFolder(String oldPath, String newPath) {
	    copyFolder(oldPath, newPath);
	    delFolder(oldPath);
	  }
	  
	  
	/**
	 * 利用PrintStream写文件 
	 * 写文件，会把原文件中的内容删除
	 * @param Path  String 如：C:/fd/jj.txt
	 * @param inBuffer String[] 如：inBuufer={"dfa","dfdf"}
	 */
	  public void writeFile(String Path,String[] inBuffer){
		  
		  try{ 
			  File file = new File(Path);
			  if(!file.exists()){
				  newFile(Path,"");  
			  }
			  FileOutputStream out=new FileOutputStream(file); 
			  PrintStream p=new PrintStream(out); 
			  for(int i=0;i<inBuffer.length;i++) 
			  {
			  p.println("This is "+i+" line");
			  p.println(inBuffer[i]);}
			  
			  }
		     catch (FileNotFoundException e){ 
			  e.printStackTrace(); 
			  } 

		  
	  }
	  
	  /**
	   * 该方法可以设定使用何种编码，有效解决中文问题。
	   * 利用StringBuffer写文件
	   * @param Path  String 如：C:/fd/jj.txt
	   * @param inBuffer String[] 如：inBuufer={"dfa","dfdf"}
	   */
	  public void StringBufferWriteFile(String Path,String[] inBuffer){
		 
		  try{
			  File file=new File(Path); 
		 if(!file.exists()) 
		  file.createNewFile(); 
		  FileOutputStream out=new FileOutputStream(file,true); 
		  for(int i=0;i<inBuffer.length;i++) 
		  {
			  out.write(inBuffer[i].toString().getBytes("utf-8"));
		  }
		  
	     out.close(); 
		  }
		  catch (IOException ex){ 
			 
			  ex.printStackTrace();
			  } 

	  }
	  
	  /** 
	  * @param path 文件目录 
	  * @param oldname 原来的文件名 
	  * @param newname 新文件名 
	  */ 
	  public void renameFile(String path,String oldname,String newname){ 
	  File oldfile=new File(path+"/"+oldname); 
	  File newfile=new File(path+"/"+newname); 
	  if(newfile.exists()) 
	  System.out.println(newname+"已经存在！"); 
	  else{ 
	  oldfile.renameTo(newfile); 
	  } 
	  } 

	  public void writeFile(String filePath,String fileContent){
		  writeFile(filePath,fileContent,"utf-8");
	  }
	  public void writeFile(String filePath,String fileContent,String encode){
			try {
				File f = new File(filePath);
				if(!f.exists()){
					f.createNewFile();
				}
				OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),encode);
				BufferedWriter writer = new BufferedWriter(write);
				writer.write(fileContent);
				writer.close();
			} catch (IOException e) {
				log.error(e.getMessage(),e);
			}
	  }
	  public String readFile(String filePath) {
			return readFile(filePath,"UTF-8");
		}
	  public String readFile(String filePath,String encode) {
			InputStream is = null;
			StringBuffer str = new StringBuffer();
			String line = ""; // 用来保存每行读取的内容
			try {
				is = new FileInputStream(filePath);
				BufferedReader reader = null;
				reader = new BufferedReader(new InputStreamReader(is, encode));
				line = reader.readLine();
				while (line != null) {
					str.append(line);
					str.append("\n");
					try {
						line = reader.readLine();
					} catch (IOException e) {
						log.error(e.getMessage(), e);
					}
				}
			} catch (FileNotFoundException e) {
				log.error(e.getMessage(), e);
			} catch (UnsupportedEncodingException e) {
				log.error(e.getMessage(), e);
			} catch (IOException e) {
				log.error(e.getMessage(), e);
			}

			return str.toString();
		}
	  public static void main(String[] arg){
		  FileOperate  fileoperate=new FileOperate();
		  fileoperate.copyFile("E:\\FC-TEST\\FTP2\\ext\\simple\\simple1.jsp", "E:\\FC-TEST\\upload\\simple1.jsp");
		 /* File[] files = fileoperate.getFileList("c:/",fileFilter);
		  for (int i = 0; i < files.length; i++) {
			  File file = files[i];
			System.out.println("files===="+files[i].getName()+"===="+file.lastModified()+"===="+file.isDirectory()+"==="+file.isAbsolute()+"===="+file.listFiles(fileFilter));
		  }*/
		
		 // System.out.println(System.getProperty("user.dir"));
		 // File file;
		 // String pathtest=System.getProperty("user.dir");
		  //String pathtest1="D:/myFTPFile/2.txt";
		 // String pathtest2="D:/myFTPrecord/myaccount/trailer.txt";
		//  String pathtest3="D:/myFTPrecord/myaccount/GIs1.txt";
		 //file=fileoperate.concatNewFile(pathtest1,pathtest2,pathtest3);
		//System.out.println(file.getAbsolutePath());
	  }
	  
	  private static FileFilter fileFilter=new FileFilter(){
		   public boolean accept(File pathname) {
		   String tmp=pathname.getName().toLowerCase();
		  if(tmp.endsWith(".doc") || tmp.endsWith(".zip")){
		   return true;
		   }
		  return false;
		   }
		  };

}
